package cn.itcast.flink.transformation;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author lilulu
 */
//使用Flink 计算引擎实现流式数据处理：从Socket接收数据，对数据进行过滤【filter】和【process】
public class TransformationProcessDemo {
    public static void main(String[] args) throws Exception {
        // 1. 执行环境-env
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 2. 数据源-source
        DataStreamSource<String> source = env.socketTextStream("node1", 9999);
        // 3. 数据转换-transformation
        SingleOutputStreamOperator<String> filter = source.filter(
                new FilterFunction<String>() {
                    @Override
                    public boolean filter(String lines) throws Exception {
                        return lines.trim().length() > 0;
                    }
                }
        );
        filter.printToErr("filter>");

        SingleOutputStreamOperator<String> process = source.process(
                new ProcessFunction<String, String>() {
                    @Override
                    public void processElement(String line, Context context, Collector<String> collector) throws Exception {
                        if (line.trim().length() > 0) {
                            collector.collect(line);
                        }
                    }
                }
        );
        process.printToErr("process>");
        // 4. 数据终端-sink
        // 5. 触发执行-execute
        env.execute("TransformationProcessDemo");
    }
}